package edu.nf.takeoutdemo.web.user;

import edu.nf.takeoutdemo.commons.base.BaseController;
import edu.nf.takeoutdemo.commons.constant.StatusConstant;
import edu.nf.takeoutdemo.commons.context.BaseContext;
import edu.nf.takeoutdemo.commons.result.Result;
import edu.nf.takeoutdemo.model.entity.AddressBook;
import edu.nf.takeoutdemo.service.AddressBookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author zjl
 * @date 2025/10/30
 */
@RestController
@RequestMapping("/user/addressBook")
@RequiredArgsConstructor
public class AddressBookController extends BaseController {

    private final AddressBookService addressBookService;

    @GetMapping("/list")
    public Result<List<AddressBook>> list(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList = addressBookService.list(addressBook);
        return success(addressBookList);
    }

    @PostMapping
    public Result<?> save(@RequestBody AddressBook addressBook){
        addressBookService.save(addressBook);
        return success();
    }


    @GetMapping("/default")
    public Result<AddressBook> getDefault(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.ENABLE);
        List<AddressBook> list = addressBookService.list(addressBook);
        if(list==null||list.isEmpty()){
            return error("没有默认地址");
        }
        return success(list.getFirst());
    }


    @PutMapping
    public Result<?> update(@RequestBody AddressBook addressBook){
        addressBookService.update(addressBook);
        return success();
    }

    @DeleteMapping
    public Result<?> deleteByID(Long id){
        addressBookService.deleteById(id);
        return success();
    }

    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable("id") Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return success(addressBook);
    }

    @PutMapping("/default")
    public Result<?> setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefault(addressBook);
        return success();
    }
}
